/**
 * 嵌入式聊天窗口集成工具
 * 版本: 1.0.0
 *
 * 使用方法:
 * 1. 在页面中引入此脚本: <script src="/embed-chat-integration.js"></script>
 * 2. 调用 EmbedChat.open() 方法打开聊天窗口
 */

;(function (global) {
  'use strict'

  // 配置选项
  const defaultConfig = {
    baseUrl: window.location.origin,
    windowFeatures:
      'width=1200,height=800,scrollbars=yes,resizable=yes,location=no,menubar=no,toolbar=no',
    windowName: 'embed-chat',
  }

  /**
   * 嵌入式聊天窗口工具类
   */
  class EmbedChatUtil {
    constructor(config = {}) {
      this.config = { ...defaultConfig, ...config }
      this.openWindows = new Map() // 跟踪打开的窗口
    }

    /**
     * 打开聊天窗口
     * @param {string} token - 用户访问令牌
     * @param {string} [datasetId] - 数据集ID（可选）
     * @param {object} [options] - 额外选项
     * @returns {Window} 返回打开的窗口对象
     */
    open(token, datasetId = null, options = {}) {
      if (!token) {
        throw new Error('Token is required')
      }

      // 构建URL
      let url = `${this.config.baseUrl}/embed-chat?token=${encodeURIComponent(token)}`

      if (datasetId) {
        url += `&dataset_id=${encodeURIComponent(datasetId)}`
      }

      // 合并窗口选项
      const windowFeatures = options.windowFeatures || this.config.windowFeatures
      const windowName = options.windowName || this.config.windowName

      // 如果已经有同名窗口且没有关闭，则聚焦到该窗口
      if (this.openWindows.has(windowName)) {
        const existingWindow = this.openWindows.get(windowName)
        if (!existingWindow.closed) {
          existingWindow.focus()
          return existingWindow
        } else {
          this.openWindows.delete(windowName)
        }
      }

      // 打开新窗口
      const chatWindow = window.open(url, windowName, windowFeatures)

      if (!chatWindow) {
        throw new Error('Failed to open chat window. Please check popup blocker settings.')
      }

      // 跟踪窗口
      this.openWindows.set(windowName, chatWindow)

      // 监听窗口关闭事件
      const checkClosed = setInterval(() => {
        if (chatWindow.closed) {
          this.openWindows.delete(windowName)
          clearInterval(checkClosed)

          // 触发关闭事件回调
          if (options.onClose && typeof options.onClose === 'function') {
            options.onClose()
          }
        }
      }, 1000)

      // 窗口加载完成后的回调
      if (options.onLoad && typeof options.onLoad === 'function') {
        chatWindow.addEventListener('load', options.onLoad)
      }

      return chatWindow
    }

    /**
     * 在iframe中嵌入聊天窗口
     * @param {string} token - 用户访问令牌
     * @param {string|HTMLElement} container - 容器元素或选择器
     * @param {string} [datasetId] - 数据集ID（可选）
     * @param {object} [options] - 额外选项
     * @returns {HTMLIFrameElement} 返回创建的iframe元素
     */
    embed(token, container, datasetId = null, options = {}) {
      if (!token) {
        throw new Error('Token is required')
      }

      // 获取容器元素
      let containerElement
      if (typeof container === 'string') {
        containerElement = document.querySelector(container)
      } else if (container instanceof HTMLElement) {
        containerElement = container
      } else {
        throw new Error('Invalid container element')
      }

      if (!containerElement) {
        throw new Error('Container element not found')
      }

      // 构建URL
      let url = `${this.config.baseUrl}/embed-chat?token=${encodeURIComponent(token)}`

      if (datasetId) {
        url += `&dataset_id=${encodeURIComponent(datasetId)}`
      }

      // 创建iframe
      const iframe = document.createElement('iframe')
      iframe.src = url
      iframe.style.width = options.width || '100%'
      iframe.style.height = options.height || '600px'
      iframe.style.border = options.border || '1px solid #e5e7eb'
      iframe.style.borderRadius = options.borderRadius || '8px'
      iframe.frameBorder = '0'

      // 添加其他属性
      if (options.id) iframe.id = options.id
      if (options.className) iframe.className = options.className

      // 清空容器并添加iframe
      containerElement.innerHTML = ''
      containerElement.appendChild(iframe)

      // 加载完成回调
      if (options.onLoad && typeof options.onLoad === 'function') {
        iframe.addEventListener('load', options.onLoad)
      }

      return iframe
    }

    /**
     * 关闭指定的聊天窗口
     * @param {string} [windowName] - 窗口名称，不指定则关闭所有窗口
     */
    close(windowName = null) {
      if (windowName) {
        const chatWindow = this.openWindows.get(windowName)
        if (chatWindow && !chatWindow.closed) {
          chatWindow.close()
          this.openWindows.delete(windowName)
        }
      } else {
        // 关闭所有窗口
        this.openWindows.forEach((chatWindow, name) => {
          if (!chatWindow.closed) {
            chatWindow.close()
          }
        })
        this.openWindows.clear()
      }
    }

    /**
     * 检查指定窗口是否打开
     * @param {string} windowName - 窗口名称
     * @returns {boolean}
     */
    isOpen(windowName = this.config.windowName) {
      const chatWindow = this.openWindows.get(windowName)
      return chatWindow && !chatWindow.closed
    }

    /**
     * 获取所有打开的窗口
     * @returns {Map} 窗口映射
     */
    getOpenWindows() {
      // 清理已关闭的窗口
      this.openWindows.forEach((chatWindow, name) => {
        if (chatWindow.closed) {
          this.openWindows.delete(name)
        }
      })
      return new Map(this.openWindows)
    }

    /**
     * 验证token格式（简单检查）
     * @param {string} token - 要验证的token
     * @returns {boolean}
     */
    validateToken(token) {
      return typeof token === 'string' && token.trim().length > 0
    }
  }

  // 创建全局实例
  const EmbedChat = new EmbedChatUtil()

  // 添加便捷方法到全局对象
  global.EmbedChat = {
    // 创建新实例（支持自定义配置）
    create: (config) => new EmbedChatUtil(config),

    // 使用默认实例的方法
    open: (token, datasetId, options) => EmbedChat.open(token, datasetId, options),
    embed: (token, container, datasetId, options) =>
      EmbedChat.embed(token, container, datasetId, options),
    close: (windowName) => EmbedChat.close(windowName),
    isOpen: (windowName) => EmbedChat.isOpen(windowName),
    getOpenWindows: () => EmbedChat.getOpenWindows(),
    validateToken: (token) => EmbedChat.validateToken(token),

    // 工具方法
    utils: {
      /**
       * 从localStorage获取当前用户token（如果存在）
       * @returns {string|null}
       */
      getCurrentToken() {
        return localStorage.getItem('token')
      },

      /**
       * 生成随机窗口名称
       * @returns {string}
       */
      generateWindowName() {
        return `embed-chat-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      },

      /**
       * 检查浏览器是否支持弹窗
       * @returns {boolean}
       */
      supportsPopup() {
        try {
          const testWindow = window.open('', '_blank', 'width=1,height=1')
          if (testWindow) {
            testWindow.close()
            return true
          }
          return false
        } catch {
          return false
        }
      },
    },
  }

  // 版本信息
  global.EmbedChat.version = '1.0.0'
})(window)

/* 使用示例:

// 1. 基本用法 - 打开新窗口
EmbedChat.open('your_token_here');

// 2. 指定数据集ID
EmbedChat.open('your_token_here', 'dataset_id_here');

// 3. 自定义选项
EmbedChat.open('your_token_here', 'dataset_id_here', {
  windowName: 'my-chat-window',
  windowFeatures: 'width=1000,height=700',
  onLoad: () => console.log('Chat window loaded'),
  onClose: () => console.log('Chat window closed')
});

// 4. 嵌入到页面中
EmbedChat.embed('your_token_here', '#chat-container', 'dataset_id_here', {
  width: '100%',
  height: '500px',
  onLoad: () => console.log('Chat iframe loaded')
});

// 5. 关闭窗口
EmbedChat.close(); // 关闭所有窗口
EmbedChat.close('my-chat-window'); // 关闭指定窗口

// 6. 检查窗口状态
if (EmbedChat.isOpen()) {
  console.log('Chat window is open');
}

// 7. 使用工具方法
const currentToken = EmbedChat.utils.getCurrentToken();
if (currentToken && EmbedChat.validateToken(currentToken)) {
  EmbedChat.open(currentToken);
}

*/
